<template>
<div v-if="goods.length>=1">
<table border="1" cellpadding="10" cellspacing="10" align="center">
  <caption><h2>{{title}}</h2></caption>
  <thead align="center">
    <tr>
      <th>结算</th>
      <th>编号</th>
      <th>商品名称</th>
      <th>商品价格</th>
      <th>商品小计</th>
      <th>购买数量</th>
      <th>操作</th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="(item,index) in goods" :key="item" align="center">
      <td>
        <label>
          <input type="checkbox" v-model="item.active"  />
        </label>
      </td>
      <td>{{index+1}}</td>
      <td>{{item.name}}</td>
      <td><small>￥</small>{{item.prices.toFixed(2)}}</td>
      <td><small>￥</small>{{(item.prices*item.num).toFixed(2)}}</td>
      <td><button @click="item.num--" :disabled="item.num<=1">-</button>{{item.num}}<button @click="item.num++">+</button></td>
      <td><a href="#" @click="deletes(index)">删除</a></td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td colspan="3" >总计：</td>
      <td colspan="2" style="border-right:none;">件数：{{sums}}&nbsp;件</td>
      <td colspan="2" align="right" style="border-left:none;">应付金额：&nbsp;&nbsp;<small>￥&nbsp;&nbsp;</small>{{totals}}&nbsp;&nbsp;元</td>
    </tr>
  </tfoot>
</table>
</div>
<div v-else class="shows">
  <h2>你没有选择的商品。购物车为空，去购物</h2>
</div>
</template>

<script>
const date = {
  title:"购物车",
  goods:[
    {id:1,name:"《茶花女》",prices:10.00,num:1,active:true},
    {id:2,name:"《平凡的世界》",prices:20.00,num:1,active:true},
    {id:3,name:"《活着》",prices:20.00,num:1,active:true},
    {id:4,name:"《兄弟》",prices:20.00,num:1,active:true},
    {id:5,name:"《骆驼祥子》",prices:20.00,num:1,active:true},
    {id:6,name:"《人生》",prices:20.00,num:1,active:true},
  ],
};
export default {
  name: "App",
  data(){
    return date;
  },
  methods:{
    deletes(e){
      this.goods.splice(e,1);
    }
  },
  computed:{
    totals(){
      // let sums = null;
      // for (let i in this.goods){
      //   sums+=this.goods[i].active?this.goods[i].num*this.goods[i].prices:0;
      // }
      let sums = this.goods.reduce((s,n)=>{
        if (n.active){
          s+=(n.prices*n.num);
        }
        return s;
      },0)
      return sums.toFixed(2);
    },
    sums(){
      return this.goods.reduce((a,b)=>a+b.num,0);
    }
  },
}
</script>

<style scoped>
table{
  border-collapse: collapse;
}
.shows{
  width: 500px;
  margin: 20px auto;
}
button{
  margin: 0 10px;
}
</style>